<template>
  <div class="permission-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <div>
            <el-button type="primary" @click="addPermission">添加权限</el-button>
            <el-button type="info" @click="loadApiEndpoints">获取API端点</el-button>
          </div>
        </div>
      </template>

      <!-- API端点权限表格 -->
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="系统权限" name="system">
          <el-table :data="permissions" style="width: 100%" v-loading="loading">
            <el-table-column prop="permissionId" label="权限ID" width="150" />
            <el-table-column prop="permissionName" label="权限名称" width="200" />
            <el-table-column prop="permissionCode" label="权限代码" width="200" />
            <el-table-column prop="permissionDescription" label="权限描述" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="editPermission(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deletePermission(scope.row.permissionId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="API端点权限" name="api">
          <el-table :data="apiEndpoints" style="width: 100%" v-loading="apiEndpointsLoading">
            <el-table-column prop="url" label="API路径" width="250" />
            <el-table-column prop="methods" label="请求方法" width="150">
              <template #default="scope">
                <el-tag 
                  v-for="method in scope.row.methods" 
                  :key="method"
                  :type="getMethodType(method)"
                  style="margin-right: 4px; margin-bottom: 4px;"
                >
                  {{ method }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="controller" label="控制器" width="150" />
            <el-table-column prop="method" label="方法" width="150" />
            <el-table-column prop="permissions" label="对应权限" width="200">
              <template #default="scope">
                <el-tag 
                  v-for="permission in scope.row.permissions" 
                  :key="permission"
                  type="success"
                  style="margin-right: 4px; margin-bottom: 4px;"
                >
                  {{ permission }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 权限编辑对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
        <el-form :model="currentPermission" label-width="120px">
          <el-form-item label="权限ID">
            <el-input v-model="currentPermission.permissionId" :disabled="!!currentPermission.permissionId" />
          </el-form-item>
          <el-form-item label="权限名称">
            <el-input v-model="currentPermission.permissionName" />
          </el-form-item>
          <el-form-item label="权限代码">
            <el-input v-model="currentPermission.permissionCode" placeholder="如：user:read, course:write" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="currentPermission.permissionDescription" type="textarea" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="savePermission">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPermissions, createPermission, updatePermission, deletePermission as deletePermissionApi, getApiEndpoints } from '@/api/permission'

const permissions = ref([])
const apiEndpoints = ref([])
const loading = ref(false)
const apiEndpointsLoading = ref(false)
const dialogVisible = ref(false)
const currentPermission = ref({})
const dialogTitle = ref('')
const activeTab = ref('system')  // 默认显示系统权限标签

// 加载权限列表
const loadPermissions = async () => {
  loading.value = true
  try {
    const response = await getPermissions()
    permissions.value = response.data
  } catch (error) {
    ElMessage.error('加载权限列表失败')
  } finally {
    loading.value = false
  }
}

// 加载API端点
const loadApiEndpoints = async () => {
  apiEndpointsLoading.value = true
  try {
    const response = await getApiEndpoints()
    apiEndpoints.value = response.data
  } catch (error) {
    ElMessage.error('加载API端点失败')
  } finally {
    apiEndpointsLoading.value = false
  }
}

// 根据HTTP方法返回标签类型
const getMethodType = (method) => {
  switch (method) {
    case 'GET':
      return 'success'
    case 'POST':
      return 'warning'
    case 'PUT':
      return 'primary'
    case 'DELETE':
      return 'danger'
    default:
      return 'info'
  }
}

// 添加权限
const addPermission = () => {
  currentPermission.value = { permissionId: '', permissionName: '', permissionCode: '', permissionDescription: '' }
  dialogTitle.value = '添加权限'
  dialogVisible.value = true
}

// 编辑权限
const editPermission = (permission) => {
  currentPermission.value = { ...permission }
  dialogTitle.value = '编辑权限'
  dialogVisible.value = true
}

// 保存权限
const savePermission = async () => {
  try {
    if (currentPermission.value.permissionId) {
      // 更新现有权限
      await updatePermission(currentPermission.value.permissionId, currentPermission.value)
      ElMessage.success('权限更新成功')
    } else {
      // 创建新权限
      await createPermission(currentPermission.value)
      ElMessage.success('权限创建成功')
    }
    
    dialogVisible.value = false
    loadPermissions() // 重新加载权限列表
  } catch (error) {
    ElMessage.error('保存权限失败')
  }
}

// 删除权限
const deletePermission = async (permissionId) => {
  try {
    await ElMessageBox.confirm(
      '确认删除这个权限吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deletePermissionApi(permissionId)
    ElMessage.success('权限删除成功')
    loadPermissions() // 重新加载权限列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除权限失败')
    }
  }
}

onMounted(() => {
  loadPermissions()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-management {
  padding: 20px;
}
</style>